package com.example.layoutandlistview;


import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class FileDownloader extends Activity implements FileDownloadConstants,
		TextWatcher {

	// instance variables
	public FileDownloader thisActivity;
	public Thread downloaderThread;
	public ProgressDialog progressDialog;

	ProgressDialog loadListFileDailog;
	AutoCompleteTextView autoTextFileNameFilter;
	ListView listViewFile;
	// Button btnFilter;

	FileAdapter fileAdapter;
	//ArrayList<FileDownload> files;
	ArrayList<FileDownload> filterFiles;
	boolean filter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		thisActivity = this;
		downloaderThread = null;
		progressDialog = null;
		setContentView(R.layout.download_activity);

		autoTextFileNameFilter = (AutoCompleteTextView) findViewById(R.id.fileNameFilter);
		autoTextFileNameFilter.addTextChangedListener(this);
		
		//autoTextFileNameFilter.getNextFocusLeftId();
		listViewFile = (ListView) findViewById(R.id.listview);
		//listViewFile.requestFocus();

		listViewFile.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				// displayMessage(files.get(arg2).getDownloadLink() + " "
				// + arg2);
				if (isOnline()) {
					if (checkSDcard("albania-0.2.4.map") == PREPARED_DOWNLOAD) {
						if (filter == true)
							downloaderThread = new DownloaderThread(
									thisActivity, filterFiles.get(arg2)
											.getDownloadLink());
						else
							downloaderThread = new DownloaderThread(
									thisActivity, AvalibleFileDownload.getFileDownloadListStatic().get(arg2)
											.getDownloadLink());
						downloaderThread.start();
					}
				} else
					displayMessage(getString(R.string.not_online));
			}

		});

		Log.i("oncreat", "sa");
		// Button button = (Button) this.findViewById(R.id.download_button);
		// button.setOnClickListener(this);

		filter = false;
		filterFiles = new ArrayList<FileDownload>();
		//files = new ArrayList<FileDownload>();
		if(isOnline()){
			if(AvalibleFileDownload.getFileDownloadListStatic().size()==0)
				loadFile();
			else
				setListView();
		}else{
			
			displayMessage(getString(R.string.not_online));
		}

	}
	
	void setListView(){
		fileAdapter = new FileAdapter(FileDownloader.this,
				android.R.layout.simple_list_item_1, AvalibleFileDownload.getFileDownloadListStatic());
		listViewFile.setAdapter(fileAdapter);
		listViewFile.requestFocus();
	} 

	void loadFile() {
		loadListFileDailog = ProgressDialog.show(this, "Please wait",
				"Loadding avalible file list...", true);

		new Thread() {
			public void run() {
				try {
					Log.i("thread", "run");
					filterFiles = FileDownload.getFileList("ok");
					for(int i = 0; i < filterFiles.size() ;i++)
						AvalibleFileDownload.getFileDownloadListStatic().add(filterFiles.get(i));
					// try{

					// Thread.sleep(10000);
					// }catch (Exception e) {
					// TODO: handle exception
					// }

				} catch (Exception e) {
					e.printStackTrace();
				}
				handlerLoadFile.sendEmptyMessage(0);
				loadListFileDailog.dismiss();
			}
		}.start();
	}

	private Handler handlerLoadFile = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			if (filterFiles.size() > 0) {
				displayMessage("File loaded");

				Log.i("size", ">0");
				fileAdapter = new FileAdapter(FileDownloader.this,
						android.R.layout.simple_list_item_1, AvalibleFileDownload.getFileDownloadListStatic());
				listViewFile.setAdapter(fileAdapter);
				listViewFile.requestFocus();
			}else
				displayMessage("Connect is error.\nPlease try again later");


		}
	};


	public Handler activityHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			/*
			 * Handling MESSAGE_UPDATE_PROGRESS_BAR: 1. Get the current
			 * progress, as indicated in the arg1 field of the Message. 2.
			 * Update the progress bar.
			 */
			case MESSAGE_UPDATE_PROGRESS_BAR:
				if (progressDialog != null) {
					int currentProgress = msg.arg1;
					progressDialog.setProgress(currentProgress);
				}
				break;

			/*
			 * Handling MESSAGE_CONNECTING_STARTED: 1. Get the URL of the file
			 * being downloaded. This is stored in the obj field of the Message.
			 * 2. Create an indeterminate progress bar. 3. Set the message that
			 * should be sent if user cancels. 4. Show the progress bar.
			 */
			case MESSAGE_CONNECTING_STARTED:
				if (msg.obj != null && msg.obj instanceof String) {
					String url = (String) msg.obj;
					// truncate the url
					if (url.length() > 16) {
						String tUrl = url.substring(0, 15);
						tUrl += "...";
						url = tUrl;
					}
					String pdTitle = thisActivity
							.getString(R.string.progress_dialog_title_connecting);
					String pdMsg = thisActivity
							.getString(R.string.progress_dialog_message_prefix_connecting);
					pdMsg += " " + url;

					dismissCurrentProgressDialog();
					progressDialog = new ProgressDialog(thisActivity);
					progressDialog.setTitle(pdTitle);
					progressDialog.setMessage(pdMsg);
					progressDialog
							.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					progressDialog.setIndeterminate(true);
					// set the message to be sent when this dialog is canceled
					Message newMsg = Message.obtain(this,
							MESSAGE_DOWNLOAD_CANCELED);
					progressDialog.setCancelMessage(newMsg);
					progressDialog.show();
					progressDialog.setCancelable(false);
				}
				break;

			/*
			 * Handling MESSAGE_DOWNLOAD_STARTED: 1. Create a progress bar with
			 * specified max value and current value 0; assign it to
			 * progressDialog. The arg1 field will contain the max value. 2. Set
			 * the title and text for the progress bar. The obj field of the
			 * Message will contain a String that represents the name of the
			 * file being downloaded. 3. Set the message that should be sent if
			 * dialog is canceled. 4. Make the progress bar visible.
			 */
			case MESSAGE_DOWNLOAD_STARTED:
				// obj will contain a String representing the file name
				if (msg.obj != null && msg.obj instanceof String) {
					int maxValue = msg.arg1;
					String fileName = (String) msg.obj;
					String pdTitle = thisActivity
							.getString(R.string.progress_dialog_title_downloading);
					String pdMsg = thisActivity
							.getString(R.string.progress_dialog_message_prefix_downloading);
					pdMsg += " " + fileName;

					dismissCurrentProgressDialog();
					progressDialog = new ProgressDialog(thisActivity);
					progressDialog.setTitle(pdTitle);
					progressDialog.setMessage(pdMsg);
					progressDialog
							.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					progressDialog.setProgress(0);
					progressDialog.setMax(maxValue);
					// set the message to be sent when this dialog is canceled
					Message newMsg = Message.obtain(this,
							MESSAGE_DOWNLOAD_CANCELED);
					progressDialog.setCancelMessage(newMsg);

					progressDialog.setCancelable(true);
					progressDialog.show();
					progressDialog.setCancelable(true);
				}
				break;

			/*
			 * Handling MESSAGE_DOWNLOAD_COMPLETE: 1. Remove the progress bar
			 * from the screen. 2. Display Toast that says download is complete.
			 */
			case MESSAGE_DOWNLOAD_COMPLETE:
				dismissCurrentProgressDialog();
				displayMessage(getString(R.string.user_message_download_complete));
				break;

			/*
			 * Handling MESSAGE_DOWNLOAD_CANCELLED: 1. Interrupt the downloader
			 * thread. 2. Remove the progress bar from the screen. 3. Display
			 * Toast that says download is complete.
			 */
			case MESSAGE_DOWNLOAD_CANCELED:
				if (downloaderThread != null) {
					downloaderThread.interrupt();
				}
				dismissCurrentProgressDialog();
				displayMessage(getString(R.string.user_message_download_canceled));
				break;

			/*
			 * Handling MESSAGE_ENCOUNTERED_ERROR: 1. Check the obj field of the
			 * message for the actual error message that will be displayed to
			 * the user. 2. Remove any progress bars from the screen. 3. Display
			 * a Toast with the error message.
			 */
			case MESSAGE_ENCOUNTERED_ERROR:
				// obj will contain a string representing the error message
				if (msg.obj != null && msg.obj instanceof String) {
					String errorMessage = (String) msg.obj;
					dismissCurrentProgressDialog();
					displayMessage(errorMessage);
				}
				break;
			/*	
			case MESSAGE_DOWNLOAD_CANCELED_BY_USER:
				downloaderThread = null;
				break;
				*/
			default:
				// nothing to do here
				break;
			}
		}
	};

	/**
	 * If there is a progress dialog, dismiss it and set progressDialog to null.
	 */
	public void dismissCurrentProgressDialog() {
		if (progressDialog != null) {
			progressDialog.hide();
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	/**
	 * Displays a message to the user, in the form of a Toast.
	 */
	public void displayMessage(String message) {
		if (message != null) {
			Toast.makeText(thisActivity, message, Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN && filter == true) {
			filter = false;
			fileAdapter = new FileAdapter(FileDownloader.this,
					android.R.layout.simple_list_item_1, AvalibleFileDownload.getFileDownloadListStatic());
			listViewFile.setAdapter(fileAdapter);
			autoTextFileNameFilter.setText("");
			autoTextFileNameFilter.setHint("File name");
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}


	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	int checkSDcard(String fileName) {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			File dir = new File(Environment.getExternalStorageDirectory()
					+ "/Bus_Application/" + fileName);
			if (dir.exists() && dir.isFile()) {
				displayMessage(getString(R.string.file_exist));
				return FILE_DOWNLOAD_EXIST;
				// do something here
				// File wallpaperDirectory = new File("/sdcard/Wallpaper/");
				// have the object build the directory structure, if needed.
				// wallpaperDirectory.mkdirs();
				// create a File object for the output file
				// File outputFile = new File(wallpaperDirectory, fileName);
				// now attach the OutputStream to the file object, instead of a
				// String representation
				// FileOutputStream fos = new FileOutputStream(outputFile);
			} else if ((dir = new File(Environment
					.getExternalStorageDirectory()
					+ "/Bus_Application")).isDirectory()) {
				return PREPARED_DOWNLOAD;
			} else {
				dir = new File(Environment.getExternalStorageDirectory()
						+ "/Bus_Application");
				dir.mkdirs();
				return PREPARED_DOWNLOAD;
			}
		} else {
			displayMessage(getString(R.string.sdcard_unmount));
			return SDcard_UNMOUNT;
		}
	}

	@Override
	public void afterTextChanged(Editable arg0) {
		// TODO Auto-generated method stub
		String str = autoTextFileNameFilter.getText().toString();
		if (str.length() > 0) {
			filterFiles.clear();
			for (int i = 0; i < AvalibleFileDownload.getFileDownloadListStatic().size(); i++) {
				if (AvalibleFileDownload.getFileDownloadListStatic().get(i).getFileName().contains(str))
					filterFiles.add(AvalibleFileDownload.getFileDownloadListStatic().get(i));
			}
			filter = true;
			fileAdapter = new FileAdapter(this,
					android.R.layout.simple_list_item_1, filterFiles);
			listViewFile.setAdapter(fileAdapter);
		} else {
			filter = false;
			fileAdapter = new FileAdapter(this,
					android.R.layout.simple_list_item_1, AvalibleFileDownload.getFileDownloadListStatic());
			listViewFile.setAdapter(fileAdapter);
		}
		Log.i("textchange", "afterTextChanged");
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		Log.i("textchange", "beforeT");
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		Log.i("textchange", "onTextChanged");

	}

}